//
//  DZNetAPI.m
//  DaoZiJinFu
//
//  Created by dzjf on 16/10/27.
//  Copyright © 2016年 dzjf. All rights reserved.
//

#import "DZNetAPI.h"
#import "AppDelegate.h"
@implementation DZNetAPI

+ (void)request:(DZRequestUtil *)request
        success:(void (^)(id response))success
        failure:(void (^)(NSError *error))failue {
    NSString *URLString = request.requestUrl;
    NSInteger timeoutInterval = [request.timeoutInterval integerValue];
    NSInteger method  = 0; // 0 post 1 get
    if ([request.httpMethod isEqualToString:@"POST"]) {
        method = 0;
    }else{
        method = 1;
    }
    request.requestUrl = nil;
    request.httpMethod = nil;
    request.timeoutInterval = nil;
    id parameters = request.mj_keyValues;
    if (request.params) {
        parameters = request.params;
    }
    // 0.设置API地址
    NSString *string = userValue(SID);
    if (string.length > 0) {
        URLString = [URLString stringByAppendingString:[NSString stringWithFormat:@"/%@/%@/",@"LDJF_SID",userValue(SID)]];
    }
    URLString = [NSString stringWithFormat:@"%@%@",BASE_URL,[URLString stringByReplacingOccurrencesOfString:@" " withString:@"%20"]];
    // 1.创建请求管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 2.申明返回的结果是二进制类型
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    // 3.如果报接受类型不一致请替换一致text/html  或者 text/plain
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    
    // 4.请求超时，时间设置
    manager.requestSerializer.timeoutInterval = timeoutInterval;

    //添加请求头
    //------   JDTSOURCE   ------
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"%d",4] forHTTPHeaderField:@"SOURCEID"];
    //------    JDTTIME    ------
    NSString *timeSp = [NSString stringWithFormat:@"%ld",(long)[[NSDate date] timeIntervalSince1970]];
    
    [manager.requestSerializer setValue:timeSp forHTTPHeaderField:@"RTIME"];
    //------  LOGINTOKEN   ------
    if (userValue(LOGIN_TOKEN)) {
        [manager.requestSerializer setValue:userValue(LOGIN_TOKEN) forHTTPHeaderField:@"LOGINTOKEN"];
    }
    //------ JDT..(hkname) ------
    if (userValue(SID) && userValue(RNS) && userValue(HKNAME)) {
        NSString *sid = userValue(SID);
        NSString *rns = userValue(RNS);
        NSString *hkname = [[NSString stringWithFormat:@"%@%@%@",sid,timeSp,rns] md5String];
        NSString *hknameParam = userValue(HKNAME);
        [manager.requestSerializer setValue:hkname forHTTPHeaderField:hknameParam];
    }
    //------ DEVICEID  ----------
    NSString *deviceID = [[UIDevice currentDevice] uniqueDeviceIdentifier];
    if (deviceID != nil) {
        [manager.requestSerializer setValue:deviceID forHTTPHeaderField:@"DEVICEID"];
    }
    //------ https  ----------
//    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"nginx" ofType:@"cer"];
//    NSData *cerData = [NSData dataWithContentsOfFile:cerPath];
//    NSSet *cerSet = [NSSet setWithObjects:cerData, nil];
//    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey];
//    securityPolicy.allowInvalidCertificates = YES;
//    //  securityPolicy.validatesDomainName = NO;
//    [securityPolicy setPinnedCertificates:cerSet];
//    manager.securityPolicy = securityPolicy;
    

    NSLog(@"\n接口名: %@ \n 请求参数:%@\n",URLString,parameters);
    switch (method) {
        case 0:{
            [manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
                NSString *responseStr =  [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                id data = [DZNetAPI dictionaryWithJsonString:responseStr];
                [theUser setObject:data[HKNAME] forKey:HKNAME];
                [theUser synchronize];
                success(data);
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                NSLog(@"%@",error);
                failue(error);
            }];
        }break;
        case 1:{
            [manager GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
                NSString *responseStr =  [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                id data = [DZNetAPI dictionaryWithJsonString:responseStr];
                [theUser setObject:data[HKNAME] forKey:HKNAME];
                [theUser synchronize];
                success(data);
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                NSLog(@"%@",error);
                failue(error);
            }];
        }break;
        default:
            break;
    }
}

+ (void)requesSync:(DZRequestUtil *)request
           success:(void (^)(id response))success
           failure:(void (^)(NSError *error))failue {
    NSString *URLString = request.requestUrl;
    NSInteger timeoutInterval = [request.timeoutInterval integerValue];
    NSInteger method  = 0; // 0 post 1 get
    NSString *httpMethod;
    if ([request.httpMethod isEqualToString:@"POST"]) {
        method = 0;
        httpMethod = @"POST";
    }else{
        method = 1;
        httpMethod = @"GET";
    }
    request.requestUrl = nil;
    request.httpMethod = nil;
    request.timeoutInterval = nil;
    id parameters = request.mj_keyValues;
    if (request.params) {
        parameters = request.params;
    }
    // 0.设置API地址
    if (userValue(SID)) {
        URLString = [URLString stringByAppendingString:[NSString stringWithFormat:@"/%@/%@/",@"JDT_SID",userValue(SID)]];
    }
    URLString = [NSString stringWithFormat:@"%@%@",BASE_URL,[URLString stringByReplacingOccurrencesOfString:@" " withString:@"%20"]];

    NSURL *requestUrl = [NSURL URLWithString:URLString];
    NSMutableURLRequest *netRequest = [NSMutableURLRequest requestWithURL:requestUrl];
    [netRequest setTimeoutInterval:timeoutInterval];
    [netRequest setHTTPMethod:httpMethod];
    
    //1>拼接请求参数:username=wxhl&password=123456&key=value&....
    NSMutableString *paramsString = [NSMutableString string];
    NSDictionary *params = parameters;
    NSArray *allKeys = params.allKeys;
    for (int i=0; i<params.count; i++) {
        NSString *key = allKeys[i];
        NSString *value = params[key];
        [paramsString appendFormat:@"%@=%@",key,value];
        if (i < params.count-1) {
            [paramsString appendString:@"&"];
        }
    }
    
    //添加请求头
    //------   JDTSOURCE   ------
    [netRequest setValue:[NSString stringWithFormat:@"%d",4] forHTTPHeaderField:@"JDTSOURCE"];
    //------    JDTTIME    ------
    NSString *timeSp = [NSString stringWithFormat:@"%ld",(long)[[NSDate date] timeIntervalSince1970]];
    [netRequest setValue:timeSp forHTTPHeaderField:@"JDTTIME"];
    //------  LOGINTOKEN   ------
    if (userValue(LOGIN_TOKEN)) {
        [netRequest setValue:userValue(LOGIN_TOKEN) forHTTPHeaderField:@"LOGINTOKEN"];
    }
    //------ JDT..(hkname) ------
    if (userValue(SID) && userValue(RNS) && userValue(HKNAME)) {
        NSString *sid = userValue(SID);
        NSString *rns = userValue(RNS);
        NSString *hkname = [[NSString stringWithFormat:@"%@%@%@",sid,timeSp,rns] md5String];
        NSString *hknameParam = userValue(HKNAME);
        [netRequest setValue:hkname forHTTPHeaderField:hknameParam];
    }
    //------ DEVICEID  ----------
    NSString *deviceID = [[UIDevice currentDevice] uniqueDeviceIdentifier];
    if (deviceID != nil) {
        [netRequest setValue:deviceID forHTTPHeaderField:@"DEVICEID"];
    }
    
    if (method == 1) {
        NSString *separe = requestUrl.query?@"&":@"?";
        NSString *paramsURL = [NSString stringWithFormat:@"%@%@%@",URLString,separe,paramsString];
        netRequest.URL = [NSURL URLWithString:paramsURL];
    }else{
        NSData *bodyData = [paramsString dataUsingEncoding:NSUTF8StringEncoding];
        [netRequest setHTTPBody:bodyData];
    }
    NSLog(@"%@  \n %@",URLString,params);
    NSError *error = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:netRequest returningResponse:nil error:&error];
    if (error) {
       failue(error);
    }else{
      id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        success(result);
    }
}


+ (BOOL)JDNetworkingStatus {
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    return delegate.JDNeStatus;
}

/*json
 * @brief 把格式化的JSON格式的字符串转换成字典
 * @param jsonString JSON格式的字符串
 * @return 返回字典
 */
+(NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&error];
    if(error) {
        NSLog(@"json解析失败：%@",error);
        return nil;
    }
    return dic;
}



@end
